package cn.zxw.common;

import cn.zxw.functionset.FunctionApp;
import cn.zxw.functionset.FunctionController;
import cn.zxw.login.Check;
import cn.zxw.login.LoginApp;
import cn.zxw.login.LoginController;
import cn.zxw.mina.ClientHandler;
import cn.zxw.prompt.PromptApp;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.input.MouseButton;
import javafx.stage.Stage;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.swing.*;

import static cn.zxw.mina.ClientHandler.msgNeedFlash;

/**
 * 功能描述:最小化托盘 <br>
 * @Author: zxw
 * @Date: 2020/7/1 16:07
 */
public class TraySystem extends Application {
    public static TrayIcon trayIcon;
    public static int X_position;
    public static int y_position;
    public static boolean min_status;
    private static TraySystem instance;

    // 图片
    private ImageIcon icon = null;
    private Logger logger = LoggerFactory.getLogger(TraySystem.class);
    public static TraySystem getInstance(){
        if(instance == null){
            instance = new TraySystem();
        }
        return instance;
    }


    /**
     * @param args
     */
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(final Stage primaryStage) throws Exception {
    }


    //右小角,最小化.
    public  void enableTray(final Stage stage) {
        try {
            //检查系统是否支持托盘
            if (!SystemTray.isSupported()) {
                //系统托盘不支持
                LoginApp.stage.setIconified(true);
                logger.info(Thread.currentThread().getStackTrace()[1].getClassName() + ":系统托盘不支持");
                return;
            }
            PopupMenu popupMenu = new PopupMenu();
            MenuItem disgnItem = new MenuItem("设置");
            MenuItem hideItem = new  MenuItem("注销账号");
            MenuItem quitItem = new  MenuItem("退出");

            ActionListener actionListener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    MenuItem item = (MenuItem) e.getSource();
                    Platform.setImplicitExit(false); //多次使用显示和隐藏设置false
                    if (item.getLabel().equals("退出")) {
                        Check check = new Check();
                        check.quit();
                        SystemTray.getSystemTray().remove(trayIcon);
                        Platform.exit();
                        return;
                    }
                    if (item.getLabel().equals("设置")) {
                        MouseEvent event;
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    LoginController loginController = new LoginController();
                                    Stage functionStage = loginController.getStage();
                                    functionStage.setX(X_position-150);
                                    functionStage.setY(y_position-150);
                                    functionStage.show();
                                    loginController.getValue();
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                            }
                        });
                    }
                    if (item.getLabel().equals("最小化")) {
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                stage.hide();
                            }
                        });
                    }
                }
            };

            MouseListener sj = new MouseListener() {
                public void mouseReleased(MouseEvent e) {

                }

                public void mousePressed(MouseEvent e) {
                }

                public void mouseExited(MouseEvent e) {
                }

                public void mouseEntered(MouseEvent e) {
                }
                public void mouseClicked(MouseEvent event) {
                    X_position = event.getX();
                    y_position = event.getY();
                    int button = event.getButton();
                    //单击操作
                    if (button == event.BUTTON1) {
                        Platform.setImplicitExit(false); //多次使用显示和隐藏设置false
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                new Check().getMessageList();
                                msgNeedFlash = false; // 列表打开了，就不要闪烁了
                            }
                        });
                    }


                    //双击操作
                    if (event.getClickCount() == 2) {

                    }
                }
            };
            quitItem.addActionListener(actionListener);
            hideItem.addActionListener(actionListener);
            disgnItem.addActionListener(actionListener);

            popupMenu.add(hideItem);
            popupMenu.add(quitItem);
            popupMenu.add(disgnItem);
            try {
                SystemTray tray = SystemTray.getSystemTray();
                // 实例化一个图标
                icon = new ImageIcon(TraySystem.class.getResource("ICON.png"));
                trayIcon = new TrayIcon(icon.getImage(), "办公助手", popupMenu);
                trayIcon.setToolTip("办公助手");
                //设置图标尺寸自动适应
                trayIcon.setImageAutoSize(true);
                tray.add(trayIcon);
                trayIcon.addMouseListener(sj);
                min_status=true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 这里可以开启检测是否有消息的线程，如果有，就闪烁图标

        } catch (Exception e) {
            //系统托盘添加失败
            logger.error(Thread.currentThread().getStackTrace()[1].getClassName() + ":系统添加失败", e);
        }

    }



    public    void Flash(){
        Thread thread = new Thread(() -> {
            try {
                if (msgNeedFlash)// 如果新消息需要闪烁
                {
                    while (msgNeedFlash){
                        try
                        {
                            // 闪动消息的空白时间
                            trayIcon.setImage(new ImageIcon("").getImage());
                            Thread.sleep(500);
                            // 闪动消息的提示图片
                            icon = new ImageIcon(TraySystem.class.getResource("ICON.png"));
                            trayIcon.setImage(icon.getImage());
                            Thread.sleep(500);
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }

                } else //如果不需要闪烁，就重置托盘图标
                {
                    trayIcon.setImage(icon.getImage());
                }
            } catch (Exception exp) {
                exp.printStackTrace();
            }
        });
        thread.setDaemon(true);
        thread.start();
    }
}
